﻿using Microsoft.Extensions.DependencyInjection;
using MyVideoPlayer.Services.DI;
using MyVideoPlayer.ViewModels;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Threading;

namespace MyVideoPlayer.Views
{
    /// <summary>
    /// _multiWinSetViewModel.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public bool IsPrimary { get; }
        private readonly DispatcherTimer _hideControlsTimer;// 定时器，用于隐藏底部面板
        private readonly MainWindowViewModel? _mainWindowViewModel;// 媒体窗口视图模型
        public MainWindow()
            : this(string.Empty, true) // 默认调用带参数的构造函数，传入 IsPrimary 为 true
        {
        }
        public MainWindow(string dataFilePath, bool isPrimary)
        {
            InitializeComponent();
            IsPrimary = isPrimary;
            try
            {
                // 通过 App.Services 获取依赖注入的服务
                var dialogService = App.Services.GetRequiredService<IOpenFileDialogService>();
                var dispatcherSevice = App.Services.GetRequiredService<IDispatcherService>();
                _mainWindowViewModel = new MainWindowViewModel(dialogService, dispatcherSevice, dataFilePath);
                this.DataContext = _mainWindowViewModel;
            }
            catch (Exception ex)
            {
                MessageBox.Show("初始化失败：" + ex.Message, "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                Application.Current.Shutdown();
            }

            // 初始化定时器
            _hideControlsTimer = new DispatcherTimer
            {
                Interval = TimeSpan.FromSeconds(3)// 设置定时器间隔为3秒隐藏
            };
            // 定时器触发事件处理程序
            _hideControlsTimer.Tick += (s, e) => HideBottomPanel();
            this.MouseMove += (s, e) => ShowBottomPanel();

        }
        /// <summary>
        /// 隐藏底部面板
        /// </summary>
        private void HideBottomPanel()
        {
            BottomPanel.Opacity = 0; // 隐藏底部面板
            TitleBar.Visibility = Visibility.Collapsed;
            _hideControlsTimer.Stop(); // 停止定时器
        }
        /// <summary>
        /// 显示底部面板
        /// </summary>
        private void ShowBottomPanel()
        {
            if (BottomPanel.Opacity == 0) // 如果底部面板是隐藏的
            {
                BottomPanel.Opacity = 1; // 显示底部面板
            }
            if (this.WindowState == WindowState.Maximized)
            {
                TitleBar.Visibility = Visibility.Visible;
            }
            else
            {
                TitleBar.Visibility = Visibility.Collapsed;
            }
            _hideControlsTimer.Stop(); // 停止定时器
            _hideControlsTimer.Start(); // 重启定时器
        }
        /// <summary>
        /// 防止主窗口关闭时，分屏窗口仍然存在，程序无法完全退出的问题
        /// </summary>
        /// <param name="e"></param>
        protected override void OnClosing(CancelEventArgs e)
        {
            // 判断分屏窗口是否存在
            if (IsPrimary && MultiWinSet.Instance != null &&
                MultiWinSet.Instance._multiWinSetViewModel.WindowMap.Count > 0)
            {
                AutoCloseMessageBox.Show("请先关闭所有分屏窗口，再关闭主窗口。", 2, this);
                e.Cancel = true; // 阻止主窗口关闭
                return;
            }
            base.OnClosing(e);
        }
        /// <summary>
        /// 窗体关闭时释放资源
        /// </summary>
        /// <param name="e"></param>
        protected override void OnClosed(EventArgs e)
        {
            _mainWindowViewModel?.Dispose();
            #region 检查窗口数量，如果没有窗口了，就关闭multiWinSet窗口
            var mainWindowCount = Application.Current.Windows
                .OfType<MainWindow>()
                .Count(w => w.IsLoaded);
            if (mainWindowCount == 0)
            {
                // 关闭多窗口设置
                MultiWinSet.Instance?.Close();
            }
            #endregion

            base.OnClosed(e);
        }
        /// <summary>
        /// 鼠标进入底部面板时显示底部面板
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BottomPanel_MouseEnter(object sender, MouseEventArgs e)
        {
            ShowBottomPanel();
        }
        /// <summary>
        /// 鼠标离开底部面板时隐藏底部面板
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BottomPanel_MouseLeave(object sender, MouseEventArgs e)
        {
            _hideControlsTimer.Start(); // 鼠标离开时重新启动定时器
        }
        /// <summary>
        /// 关闭按钮点击事件处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnClose_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        protected override void OnSourceInitialized(EventArgs e)
        {
            base.OnSourceInitialized(e);
            var hwnd = new WindowInteropHelper(this).Handle;
            int useDark = 1;
            DwmSetWindowAttribute(hwnd, 20, ref useDark, sizeof(int)); // 20 = DWMWA_USE_IMMERSIVE_DARK_MODE
        }
        /// <summary>
        /// 通过api设置窗口属性，启用暗黑模式
        /// </summary>
        [DllImport("dwmapi.dll")]
        private static extern int DwmSetWindowAttribute(IntPtr hwnd, int attr, ref int attrValue, int attrSize);

        private void Grid_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (e.ClickCount == 2)
            {
                _mainWindowViewModel!.MaximizedCommand.Execute(this);
            }
        }
    }
}
